import { getSubmitOrderInfo, postSubmit, Pay } from "@/services";

const state = {
  userAddr: {},
  addrId: 0,
  detailOrder: {},
  submintList: [],
  actualTotal: 0,
  orderNumbers: "",
};

const getters = {};

const mutations = {
  update(state, payload) {
    for (let key in payload) {
      state[key] = payload[key];
    }
  },
};

const actions = {
  async getSubmitOrderInfo({ commit }, payload) {
    let data,result;
    if (payload.hasOwnProperty('basketIds')) {
       data = {
        addrId: 0,
        basketIds: payload.basketIds.split(','),
        couponIds: [],
        userChangeCoupon: 1,
      }
      result = await getSubmitOrderInfo(data);
    } else {
       data = {
        addrId: 0,
        orderItem: JSON.parse(payload.orderItem),
        couponIds: [],
        userChangeCoupon: 1,
      }
     result = await getSubmitOrderInfo(data);
    }
    if (result) {
      commit("update", {
        submintList:
          result.shopCartOrders[0].shopCartItemDiscounts[0].shopCartItems,
        actualTotal: result.total,
        userAddr: result.userAddr,
      });
    }
  },
  async postSubmit({ commit }, payload) {
    let result = await postSubmit(payload);
    if (result) {
      commit("update", {
        orderNumbers: result.orderNumbers,
      });
    }
  },
  async postpay({ commit }, payload) {
    let result = await Pay(payload);
    if (result) {
      wx.requestPayment({
        timeStamp: result.timeStamp,
        nonceStr: result.nonceStr,
        package: result.packageValue,
        signType: result.signType,
        paySign: result.paySign,
        success(result) {
          if (result.errMsg == "OK") {
            wx.navigateTo({
              url: "/pages/basket/index",
            });
          }
        },
        fail(result) {
          wx.navigateTo({
            url: "/pages/pay-result/index",
          });
        },
      });
    }
  },
};

export default {
  namespaced: true,
  modules: {},
  state,
  getters,
  mutations,
  actions,
};
